package com.fauks.ssm.springmvc.converter;

import org.springframework.beans.TypeMismatchException;
import org.springframework.core.convert.converter.Converter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Pattern;

//实现String转Date
public class MyDateConverter implements Converter<String, Date> {
    @Override
    public Date convert(String source) {
        SimpleDateFormat format = getDateFormat(source);
        try {
            return format.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }

    private SimpleDateFormat getDateFormat(String source) {
        //是否正则表达式匹配日期的输入类型
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        if (Pattern.matches("^\\d{4}-\\d{2}-\\d{2}$", source)) {
            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        } else if (Pattern.matches("^\\d{4}/\\d{2}/\\d{2}$", source)) {
            simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        } else {
            //抛出异常，用于全局异常捕获统一处理
            throw new TypeMismatchException("", Date.class);
        }
        return simpleDateFormat;
    }
}
